<template>
  <div class="">
    <PageTitle :select="0" showTimeType showDay @changeTime="changeTime" @changeType="changeType"></PageTitle>
    <div class="cont" :style="{ height: `${clientHeight / scaleX - 90}px` }">
      <el-scrollbar :style="{height: `${clientHeight / scaleX - 120}px`}">
        <div class="rowbox" style="margin-bottom: 25px">
          <rowItem title="能耗">
            <div class="box1">
              <indexItem v-for="(item, i) in oneclist" :key="i" :title="item.name" :name2="item.name"
                :value2="item.value"></indexItem>
            </div>
          </rowItem>
          <rowItem title="安全生产统计">
            <div class="box1">
              <div class="safetyBox">
                <!-- <div class="tit">
                  <el-row>
                    <el-col :span="12" class="titText">本月安全天数</el-col>
                    <el-col :span="12" class="titValue">{{ safetyNum }}</el-col>
                  </el-row>
                </div> -->
                <div class="safetyItems">
                    <indexCircle @click="showWarnImgDiag(item.type, item.name)" :name="item.name" :values="item.value" :color="item.color" v-for="(item, index) in alarm"
                      :key="index">
                    </indexCircle>
                </div>
              </div>
              <!-- <ModelItem1 class="models" v-for="(item, i) in 6"></ModelItem1> -->
            </div>
          </rowItem>
          <rowItem title="碳排放">
            <div class="box1">
              <indexItem v-for="(item, i) in clist" :key="i" :title="item.name" :name2="item.name" :value2="item.value">
              </indexItem>
            </div>
          </rowItem>
        </div>
        <div class="rowbox">
          <rowItem title="设备稼动率"><!--订单正品率及-->
            <div class="box2">
              <CurveChart :data="zhengPinJiaDongli"></CurveChart>
            </div>
          </rowItem>
          <rowItem title="正品率">
            <div class="box2">
              <CurveChart :data="hege" :key="JSON.stringify(hege)"></CurveChart>
            </div>
          </rowItem>
          <rowItem title="计划达成率"><!--生产合格率-->
            <div class="box2">
              <CurveChart :data="shengchanRatePlan" :key="JSON.stringify(shengchanRatePlan)"></CurveChart>
            </div>
          </rowItem>
        </div>
        <div class="rowbox" style="margin-bottom: 20px">
          <rowItem title="涂层超胶总量">
            <div class="box3">
              <!-- <indexCoumn :data="coumnData"></indexCoumn> -->
              <ColumnChart :data="coumnData" :key="JSON.stringify(coumnData)"></ColumnChart>
            </div>
          </rowItem>
          <rowItem title="产品损益及订单损益">
            <div class="box3">
              <el-carousel direction="vertical" height="210px" :interval="15000" :autoplay="false">
                <el-carousel-item>
                  <div style="text-align: center;">订单损益</div>
                  <div style="height: 183px;width: 100%;">
                    <CurveChart :isGroup="true" :data="sunyiDingdan" :key="JSON.stringify(sunyiDingdan)"></CurveChart>
                  </div>
                </el-carousel-item>
                <el-carousel-item>
                  <div style="flex: 1;height: 25px;right: 0;">
                    <el-row class="radioBox">
                      <el-col :span="12" :class="sunyitimeType === 0 ? 'selectTime' : ''"
                        @click="selectTimeType(0)">周</el-col>
                      <el-col :span="12" :class="sunyitimeType === 1 ? 'selectTime' : ''"
                        @click="selectTimeType(1)">月</el-col>
                    </el-row>
                  </div>
                  <div style="height: 185px;width: 100%;">
                    <ColumnChart :data="sunyiGongchang" :key="JSON.stringify(sunyiGongchang)" unit="万"></ColumnChart>
                  </div>
                </el-carousel-item>
              </el-carousel>
            </div>
          </rowItem>
          <!-- <rowItem title="订单总发货米数">
            <div class="box3">
              <ColumnChart :data="fahuo" :key="JSON.stringify(fahuo)" unit="米"></ColumnChart>
            </div>
          </rowItem> -->
          <rowItem title="客户损益">
            <div class="box3">
              <ColumnChart :data="sunyiKehu" :key="JSON.stringify(sunyiKehu)" unit="万"></ColumnChart>
            </div>
          </rowItem>
        </div>
      </el-scrollbar>
    </div>
    <el-dialog v-model="dialogTableVisible" :modal="modelLoading" :title="imgTitle" width="1600" >
      <div class="warn-img-col">
        <el-image 
          style="width: 100px; height: 120px;margin-right: 10px;"
          :src="item" 
          v-for="(item,i) in imgsWarnList"
          :key="i"
          :preview-src-list="imgsWarnList">
        </el-image>
      </div>
      </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { useBaseDataStore } from "@/store";
import { computed, onBeforeMount, onBeforeUnmount, ref, reactive } from "vue";
import indexItem from "./cpns/index-item.vue";
import indexCircle from "./cpns/index-circle.vue";
// import indexModel from "./cpns/index-model.vue";
// import indexGauge from "./cpns/index-gauge.vue";
// import indexCoumn from "./cpns/index-coumn.vue";
import { getDapingList, getDataSyncex, getDataSyncexCL } from "@/api/timing";
import moment from "moment";
import { getEnergy, getstatistics, getWarnImgType, getWarnImg } from "@/api/energyapi";
import { yichang, erchang, fuhe, biaotu, lixin } from "./config/indexConfig";
import { yichangDevice, erchangDevice, fuheDevice, biaotuDevice, lixinDevice } from "./config/deviceConfig";
import { getSafety } from "@/api/rtspapi";
import { getDeviceParam } from "@/api/deviceapi";
import { INAPSDevice, InGongChang, InJiaDongLi, InPlanDevoce } from "@/types/APSData";
import { reduce } from "echarts/types/src/export/api/util.js";
import { imgRequstUrl } from "../../../public/baseConfig.json";
/** 数据 */
interface State {
  /** 数据状态 */
  loading: boolean;
  /** 时间定时器 */
  timer: NodeJS.Timeout | undefined;
}
/** @api */
const baseDataStore = useBaseDataStore();
/** @数据 */
//碳排放列表
const clist = ref<{ name: string; value: string; num: number }[]>([
  { name: "一厂", value: "0", num: 0 },
  { name: "复合厂", value: "0", num: 0 },
  { name: "裱涂厂", value: "0", num: 0 },
  { name: "离型纸厂", value: "0", num: 0 },
  { name: "二厂", value: "0", num: 0 },
  { name: "厂区总览", value: "0", num: 0 },
]);
//能耗数据展示
const defaultClist = ref<{ name: string; value: string; num: number }[]>([
  { name: "一厂", value: "0", num: 0 },
  { name: "复合厂", value: "0", num: 0 },
  { name: "裱涂厂", value: "0", num: 0 },
  { name: "离型纸厂", value: "0", num: 0 },
  { name: "二厂", value: "0", num: 0 },
  { name: "厂区总览", value: "0", num: 0 },
]);
/** 入库量 */
const ruku = ref<Info[]>([]);
/** 生产量 */
const production = reactive<Info[]>([]);
/** 达成率*/
const dachengList = reactive<Info[]>([]);
/** 工厂稼动力列表 */
const plantLiset = ref<InJiaDongLi[]>([
  { name: "一厂", value: 0, planTime: 0 },
  { name: "复合厂", value: 0, planTime: 0 },
  { name: "裱涂厂", value: 0, planTime: 0 },
  //{ name: "离型纸厂", value: 0, planTime: 0 },
  { name: "二厂", value: 0, planTime: 0 },
]);
/** 设备实际运行时间列表 */
const plantLisetRuntime = ref<INAPSDevice[]>([]);
/** 当天设备计划，用于计算稼动力 */
const currentDayPlan = ref<InPlanDevoce>({});
/** 工厂顺序，用户显示数据排序 */
const nameSort = ref<InGongChang[]>(["一厂", "复合厂", "裱涂厂", "离型纸厂", "二厂"]);
/** 动力 */
const dongli = ref<Info[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  //{ Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
])
interface Info {
  Group?: string;
  Day?: string;
  Week?: string;
  name?: string;
  type?: string;
  value?: string | number;
  x?: string;
  y?: number | string;
}
/** 正品率 */
const zhengpin = ref<Info[]>([
  { name: "一厂", type: "正品率", value: "0",Day: "0", Week: "0" },
  { name: "复合厂", type: "正品率", value: "0", Day: "0", Week: "0" },
  { name: "裱涂厂", type: "正品率", value: "0", Day: "0", Week: "0" },
  //{ name: "离型纸厂", type: "正品率", value: "0", Day: "0", Week: "0" },
  { name: "二厂", type: "正品率", value: "0", Day: "0", Week: "0" },
]);
/** 产量对比 */
// const dacheng = ref<Info[]>([
//   { Group: "一厂", Day: "0", Week: "0" },
//   { Group: "复合厂", Day: "0", Week: "0" },
//   { Group: "裱涂厂", Day: "0", Week: "0" },
//   { Group: "离型纸厂", Day: "0", Week: "0" },
//   { Group: "二厂", Day: "0", Week: "0" },
// ]);
/** 合格率 */
const hege = ref<Info[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  //{ Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
]);
/** 发货量 */
const fahuo = ref<Info[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  { Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
]);
/** 超胶量 */
const chaojiao = ref<{ Group?: string; Day?: string; Week?: string, type?: string, name?: string, value?: any }[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  //{ Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
]);
const sunyiGongchang = ref<Info[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  //{ Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
]);
const sunyiDingdan = ref<Info[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  //{ Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
]);
const sunyiKehu = ref<Info[]>([
  { Group: "一厂", Day: "0", Week: "0" },
  { Group: "复合厂", Day: "0", Week: "0" },
  { Group: "裱涂厂", Day: "0", Week: "0" },
  //{ Group: "离型纸厂", Day: "0", Week: "0" },
  { Group: "二厂", Day: "0", Week: "0" },
]);
const alarm = ref<{ name: string, value: string | number, color: string, type: string }[]>([
  { name: '抽烟识别报警', value: '0', color: 'orange', type: '抽烟' },
  { name: '卷绕报警数量', value: '0', color: 'orange', type: '卷绕' },
  { name: '浓度报警数量', value: '0', color: 'orange', type: '浓度' },
  { name: '明火报警数量', value: '0', color: 'yellow', type: '明火' },
  { name: '打电话数量', value: '0', color: 'yellow', type: '打电话' },
  { name: '玩手机数量', value: '0', color: 'yellow', type: '玩手机' }
])

/** 选择时间类型 */
const timeType = ref<number>(0);
/** 损益时间类型 */
const sunyitimeType = ref<number>(0);
/** 当前时间 */
const timeValue = ref<string>(moment().format("YYYY-MM-DD"));
//所有厂id
const ids = ref<string[]>([
  "5023903988659200"
  // "6213912817380352", // 一
  // "6214347951254529", //复合
  // "6214349763193856", // 裱涂
  // "6214657457335296", // 离形
  // "6214340367952896", // 二
  // "5023829028058112", // 总览
]);
//所有厂id
const idClict = ref<string[]>([
  "6213912817380352", // 一
  "6214347951254529", //复合
  "6214349763193856", // 裱涂
  "6214657457335296", // 离形
  "6214340367952896", // 二
  "5023829028058112", // 总览
]);
const safetyNum = ref(0);
const chanliang = ref([]);
const imgWarnTypeList = ref(Array);
const imgsWarnList = ref<[]>([]);
const dialogTableVisible = ref(false);
const imgTitle = ref();
const modelLoading = ref(false);
//计划产量数据
const planChanLiang = ref<Info[]>([]);
/** 数据 */
let state = ref<State>({
  loading: false,
  timer: undefined,
});
/** 生命周期 */
onBeforeMount(() => {
  getData();
  //getnenghao();
  getWarningData();
  getorderForm();
  getSafetyFun();
  //getJiadonglvFun();
  getDataCL();
  setTimer();
});
onBeforeUnmount(() => {
  clearTimeout(state.value.timer);
})
/** 方法 */
/** 定时器 */
function setTimer() {
  timeValue.value = moment().format("YYYY-MM-DD");
  getData();
  getnenghao();
  getWarningData();
  getorderForm();
  getSafetyFun();
  //getJiadonglvFun();
  clearTimeout(state.value.timer);
  state.value.timer = setTimeout(() => {
    setTimer();
  }, 1000 * 60 * 5);
}
/** 改变日、周 */
const selectTimeType = (type: number) => {
  sunyitimeType.value = type;
  sunyiGongchang.value = sunyiGongchang.value?.map((item: any) => {
          item.y = sunyitimeType.value ? Number(item.Week):Number(item.Day);
          return item;
      });
};
/*获取产能数据*/
function getDataCL(){
  const startTime = moment(timeValue.value).startOf("isoWeek");
  const startDate = timeType.value ? startTime.format("YYYY-MM-DD"): moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD');
  const endFate = timeType.value ? startTime.add(6, "days").format("YYYY-MM-DD"): moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD');
  getDataSyncexCL(`${startDate} 00:00`, 
  `${endFate} 23:59`).then((res)=>{
    // let obj = {};
    // res.data.DATA = res.data.DATA.reduce(function(a: any, b: any) {
    //     obj[b?.sOrderNo] ? '' : obj[b?.sOrderNo] = true && a.push(b);
    //     return a;
    // }, []);
    //n根据卡号去重
    // let map = new Map();
    // for (let item of res.data.DATA) {
    //     if (!map.has(item?.sCardNo+item?.sWorkingProcedureName)) {
    //         map.set(item.sCardNo, item);
    //     }
    // }
    // res.data.DATA = [...map.values()];
    let dataType = [
      {name: "一厂",value: 0,planTime: 0,type: '设备稼动力'},
      {name: "复合厂",value: 0, planTime: 0,type: '设备稼动力'},
      {name: "裱涂厂",value: 0,planTime: 0,type: '设备稼动力'},
      //{name: "离型纸厂",value: 0,planTime: 0,type: '设备稼动力'},
      {name: "二厂",value: 0,planTime: 0,type: '设备稼动力'},
    ]
    dataType = dataType.map((ele: any)=>{
      if(ele.name === "一厂"){
        //yichangDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2: any)=>{
            //if(dev === ele2?.sEquipmentName){
            if((ele2?.sWorkerGroupName?.includes("涂层") || ele2?.sWorkerGroupName?.includes("压光") || ele2?.sWorkerGroupName?.includes("水洗"))
             && !ele2?.sWorkerGroupName?.includes("二分")){
              ele.value = ele.value + ele2?.nJXTrackQty;
            }
          })
        //})
      }else if(ele.name === "二厂"){
        //erchangDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2: any)=>{
            //if(dev === ele2?.sEquipmentName){
            if(ele2?.sWorkerGroupName?.includes("二分")){
              ele.value = ele.value + ele2?.nJXTrackQty;
            }
          })
        //})
      }else if(ele.name === "复合厂"){
        //fuheDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2: any)=>{
            //if(dev === ele2?.sEquipmentName){
            if(ele2?.sWorkerGroupName?.includes("复合")){
              ele.value = ele.value + ele2?.nJXTrackQty;
            }
          })
        //})
      }else if(ele.name === "裱涂厂"){
        //biaotuDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2: any)=>{
            //if(dev === ele2?.sEquipmentName){
            if(ele2?.sWorkerGroupName?.includes("裱涂")){
              ele.value = ele.value + ele2?.nJXTrackQty;
            }
          })
      //})
      // }else if(ele.name === "离型纸厂"){
      //   lixinDevice?.forEach((dev: any)=>{
      //     res.data.DATA.forEach((ele2)=>{
      //       if(dev === ele2?.sEquipmentName){
      //         ele.value = ele.value + ele2?.nJXTrackQty;
      //       }
      //     })
      //   })
      }
      return ele;
    });
    dachengList.splice(0,dachengList.length);
    dachengList.push(...dataType);
    jiadonglv.value = JSON.parse(JSON.stringify(dataType));
    jiadonglv.value = jiadonglv.value?.map((ele)=>{
      if(ele.name === "一厂"){
        ele.value = Number(((Number(ele.value) / (72000*10))* 100).toFixed(2));
      }else if(ele.name === "复合厂"){
        ele.value = Number(((Number(ele.value) / (72000*7))* 100).toFixed(2));
      }else if(ele.name === "裱涂厂"){
        ele.value = Number(((Number(ele.value) / (72000*3))* 100).toFixed(2));
      // }else if(ele.name === "离型纸厂"){
      //   ele.value = Number(((Number(ele.value) / (72000*2))* 100).toFixed(2));
      }else if(ele.name === "二厂"){
        ele.value = Number(((Number(ele.value) / (72000*14))* 100).toFixed(2));
      }
      return ele;
    });
    //获取产量（刷卡米数）
    let shuaKaType = [
      {name: "一厂",value: 0,planTime: 0,type: '设备稼动力'},
      {name: "复合厂",value: 0, planTime: 0,type: '设备稼动力'},
      {name: "裱涂厂",value: 0,planTime: 0,type: '设备稼动力'},
      //{name: "离型纸厂",value: 0,planTime: 0,type: '设备稼动力'},
      {name: "二厂",value: 0,planTime: 0,type: '设备稼动力'},
    ]
    shuaKaType = shuaKaType.map((ele: any)=>{
      if(ele.name === "一厂"){
        yichangDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2)=>{
            if(dev === ele2?.sEquipmentName){
              ele.value += ele2?.nTrackQty;
            }
          })
        })
      }else if(ele.name === "二厂"){
        erchangDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2)=>{
            if(dev === ele2?.sEquipmentName){
              ele.value += ele2?.nTrackQty;
            }
          })
        })
      }else if(ele.name === "复合厂"){
        fuheDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2)=>{
            if(dev === ele2?.sEquipmentName){
              ele.value += ele2?.nTrackQty;
            }
          })
        })
      }else if(ele.name === "裱涂厂"){
        biaotuDevice?.forEach((dev: any)=>{
          res.data.DATA.forEach((ele2)=>{
            if(dev === ele2?.sEquipmentName){
              ele.value += ele2?.nTrackQty;
            }
          })
      })
      // }else if(ele.name === "离型纸厂"){
      //   lixinDevice?.forEach((dev: any)=>{
      //     res.data.DATA.forEach((ele2)=>{
      //       if(dev === ele2?.sEquipmentName){
      //         ele.value += ele2?.nTrackQty;
      //       }
      //     })
      //   })
      }
      return ele;
    });
    planChanLiang.value = shuaKaType;
  });
}
/** 获取数据 */
async function getData() {
  getDataSyncex("正品率", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    zhengpin.value = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
    zhengpin.value = zhengpin.value?.map((ele: Info)=>{
      ele.value = Number((timeType.value ? ele.Week : ele.Day)?.replace('%',''));
      ele.type = '正品率';
      ele.name = ele.Group;
      return ele
    })
  });
  // getDataSyncex("产量对比", timeValue.value).then((res) => {
  //   dacheng.value = res.data.DATA ?? [];
  // });
  //合格率
  getDataSyncex("异常数", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    hege.value = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
    hege.value = hege.value?.filter((ele: Info)=>{
      ele.value = Number((timeType.value ? ele.Week : ele.Day)?.replace('%',''));
      ele.type = '正品率';//'质量合格率';
      ele.name = ele.Group;
      if(ele.name !== "离型纸厂")return ele
    })
  });
  getDataSyncex("超胶量", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    chaojiao.value = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
    chaojiao.value = chaojiao.value?.filter((ele: Info)=>{
      if(ele.Group !== "离型纸厂")return ele
    })
  });
  getDataSyncex("入库数", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    ruku.value = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
  });
  getDataSyncex("发货量", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    fahuo.value = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
    fahuo.value = fahuo.value?.map((ele: Info)=>{
      ele.x = ele.Group;
      ele.y = Number(timeType.value ? ele.Week : ele.Day);
      ele.name = '米数';
      ele.type = '米';
      return ele
    })
  });
  getDataSyncex("工厂损益", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    sunyiGongchang.value = (res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? []).map((item: any) => {
        return {
          Group: item.Group,
          Day: (Number(item.Week) / 10000).toFixed(0),// + '万',
          Week: (Number(item.Month) / 10000).toFixed(0),// + '万',
          x: item.Group,
          y: sunyitimeType.value ? Number((Number(item.Month) / 10000).toFixed(0)):Number((Number(item.Week) / 10000).toFixed(0)),
          name: '金额',
          type: '万'
        };
    });
    sunyiGongchang.value = sunyiGongchang.value?.filter((ele)=>{
      if(ele.Group !== "离型纸厂"){
        return ele
      }
    })
  });
  getDataSyncex("订单损益", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    const list: Info[] = [];
    const data: any[] = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
    const data2 = data.sort((a, b) => b.Amount - a.Amount)
    data2.forEach((item) => {
      list.push({
        Group: item.CustomerName + "(" + item.OrderNo + ")",
        Day: item.Amount + '元',
        Week: item.Amount + '元',
        x: item.CustomerName + "(" + item.OrderNo + ")",
        value: Number(item.Amount),
        name: item.CustomerName + "(" + item.OrderNo + ")",
        type: item.CustomerName + "(" + item.OrderNo + ")"
      });
    });

    sunyiDingdan.value = list.slice(0, 5);
  });
  getDataSyncex("客户损益", moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD')).then((res) => {
    let list: Info[] = [];
    const data: any[] = res.data.DATA.sort((a, b) => nameSort.value.findIndex(val => a.Group === val) - nameSort.value.findIndex(val => b.Group === val)) as Info[] ?? [];
    data.forEach((item) => {
      list.push({
        Group: item.sCustomerName + "(" + item.Group + ")",
        Day: item.Amount,
        Week: item.Amount,
      });
    });
    list.sort((a, b) => Number(b.Day) - Number(a.Day));
    const info = list.map(item => {
      return {
        Group: item.Group,
        Day: (Number(item.Day) / 10000).toFixed(0) + '万',
        Week: (Number(item.Week) / 10000).toFixed(0) + '万',
        y: timeType.value ? Number((Number(item.Week) / 10000).toFixed(0)): Number((Number(item.Day) / 10000).toFixed(0)),
        x: item.Group,
      }
    })
    sunyiKehu.value = info.slice(0, 10);
  });
}
/** 获取能耗数据 */
async function getnenghao() {
  const dataType = [1,2,3,4];
  const date = moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD') + "T00:00:00Z";
  // 日
  if (timeType.value == 0) {
    const token: string = baseDataStore.getBaseData("token");
    const list = idClict.value.map((id) => getEnergy(id, "DAY", date, 9, token));
    Promise.all(list).then((res) => {
      res.map((itemRt,index: number) =>{
        let numCount = 0;
        let unit = '';
        itemRt.data.data?.forEach((ele: any)=>{
          numCount += ele?.usage?.realValue;
          unit = ele?.usage?.unit;
        })
        clist.value.forEach((item, i) => {
          if(index != i)return
          item.num = Number(Number(numCount).toFixed(2)) ?? 0;
          item.value = item.num + unit;
        });
        return numCount;
      });
    });
    //获取总能耗数据
    dataType.forEach((ele)=>{
      const list2 = ids.value.map((id) => getEnergy(id, "DAY", date, ele, token));
      Promise.all(list2).then((res) => {
        res.map((itemRate) =>{
          let numCount = 0;
          let unit = '';
          itemRate.data.data?.forEach((ele: any)=>{
            numCount = ele?.usage?.realValue || 0;
            unit = ele?.usage?.unit;
            defaultClist.value.forEach((item) => {
              if(item.name == ele?.name){
                item.num += Number(numCount) ?? 0;
                item.value = item.num + unit;
              }
            });
          })
        });
      });
    })
  } else {
    clist.value.forEach((item, i) => {
      item.num =  0;
      item.value = '';
    });
    // 周
    const startTime = moment(date).startOf("isoWeek");
    const dateList = [
      startTime.format("YYYY-MM-DD") + "T00:00:00Z",
      startTime.add(1, "days").format("YYYY-MM-DD") + "T00:00:00Z",
      startTime.add(1, "days").format("YYYY-MM-DD") + "T00:00:00Z",
      startTime.add(1, "days").format("YYYY-MM-DD") + "T00:00:00Z",
      startTime.add(1, "days").format("YYYY-MM-DD") + "T00:00:00Z",
      startTime.add(1, "days").format("YYYY-MM-DD") + "T00:00:00Z",
      startTime.add(1, "days").format("YYYY-MM-DD") + "T00:00:00Z",
    ];
    idClict.value.forEach((id, index: number) => {
      const token: string = baseDataStore.getBaseData("token");
      const list = dateList.map((item) => getEnergy(id, "DAY", item, 9, token));
      Promise.all(list).then((res) => {
        res.map((item) =>{
          let numCount = 0;
          let unit = '';
          item.data.data?.forEach((ele: any)=>{
            numCount += ele?.usage?.realValue;
            unit = ele?.usage?.unit;
          })
          clist.value.forEach((item, i) => {
            if(index != i)return
            item.num += Number(numCount) ?? 0;
            item.value = item.num + unit;
          });
          return numCount;
        });
      });
    });
    //获取总能耗数据
    dataType.forEach((ele)=>{
      ids.value.forEach((id) => {
        const token: string = baseDataStore.getBaseData("token");
        const list = dateList.map((item) => getEnergy(id, "DAY", item, ele, token));
        Promise.all(list).then((res) => {
          res.map((itemRate) =>{
            let numCount = 0;
            let unit = '';
            itemRate.data.data?.forEach((ele: any)=>{
              numCount = ele?.usage?.realValue;
              unit = ele?.usage?.unit;
              defaultClist.value.forEach((item) => {
                if(item.name == ele?.name){
                  item.num += Number(numCount) ?? 0;
                  item.value = item.num + unit;
                  //console.log(item.num,item)
                }
              });
            })
            return numCount;
          });
        });
      });
    })
  }
}
// /** 获取计划订单数据 */
function getorderForm() {
  /** 日期 */
  const dayStr = moment(timeValue.value).subtract(1, 'day').format('YYYY-MM-DD');
  getDapingList({ day: dayStr }).then((res) => {
    let yichangData: any[] = [];
    let erchangData: any[] = [];
    let fuheData: any[] = [];
    let biaotuData: any[] = [];
    let lixinData: any[] = [];
    const list = [];
    for (const key in res.data.data) {
      for (const key2 in res.data.data[key]) {
        //console.log(yichang,key2,'yichang',yichang.includes(key2))
        list.push(res.data.data[key][key2]);
        const key3 = key2?.split('/')[0];
        if (yichang.includes(key3))
          yichangData.push(...res.data.data[key][key2]);
        if (erchang.includes(key3))
          erchangData.push(...res.data.data[key][key2]);
        if (fuhe.includes(key3)) fuheData.push(...res.data.data[key][key2]);
        if (biaotu.includes(key3)) biaotuData.push(...res.data.data[key][key2]);
        //if (lixin.includes(key3)) lixinData.push(...res.data.data[key][key2]);
      }
    }
    const yichangNum = handleData(yichangData);
    const erchangNum = handleData(erchangData);
    const fuheNum = handleData(fuheData);
    const biaotuNum = handleData(biaotuData);
    //const lixinNum = handleData(lixinData);
    // 稼动率
    const yichangNum2 = handleData2(yichangData);
    const erchangNum2 = handleData2(erchangData);
    const fuheNum2 = handleData2(fuheData);
    const biaotuNum2 = handleData2(biaotuData);
    //const lixinNum2 = handleData2(lixinData);
    // console.log('数据分组', yichangData)
    // console.log('数据分组', erchangData)
    // console.log('数据分组', fuheData)
    // console.log('数据分组', biaotuData)
    // console.log('数据分组', lixinData)

    // console.log("米数", yichangNum);
    // console.log("米数", erchangNum);
    // console.log("米数", fuheNum);
    // console.log("米数", biaotuNum);
    // console.log("米数", lixinNum);

    // console.log("运行时间", yichangNum2);
    // console.log("运行时间", erchangNum2);
    // console.log("运行时间", fuheNum2);
    // console.log("运行时间", biaotuNum2);
    // console.log("运行时间", lixinNum2);
    const data: Info[] = [
      {
        Group: '一厂',
        Week: yichangNum,
        Day: yichangNum
      },
      {
        Group: '复合厂',
        Week: fuheNum,
        Day: fuheNum
      },
      {
        Group: '裱涂厂',
        Week: biaotuNum,
        Day: biaotuNum
      },
      // {
      //   Group: '离型纸厂',
      //   Week: lixinNum,
      //   Day: lixinNum
      // },
      {
        Group: '二厂',
        Week: erchangNum,
        Day: erchangNum
      },
    ]
    const data2: Info[] = [
      {
        Group: '一厂',
        Week: yichangNum2.toString(),
        Day: yichangNum2.toString()
      },
      {
        Group: '二厂',
        Week: erchangNum2.toString(),
        Day: erchangNum2.toString()
      },
      {
        Group: '复合厂',
        Week: fuheNum2.toString(),
        Day: fuheNum2.toString()
      },
      {
        Group: '裱涂厂',
        Week: biaotuNum2.toString(),
        Day: biaotuNum2.toString()
      },
      // {
      //   Group: '离型纸厂',
      //   Week: lixinNum2.toString(),
      //   Day: lixinNum2.toString()
      // },
    ]
    production.splice(0, production.length);
    production.push(...data);
    dongli.value = data2;
  });
}
/** 生产计划总数 */
function handleData(data: any[]) {
  //console.log(moment(timeValue.value).subtract(1, 'day').startOf('day').format('YYYY-MM-DD'),moment(timeValue.value).subtract(1, 'day').endOf('day').format('YYYY-MM-DD'),'---------')
  const startNum = moment(timeValue.value).subtract(1, 'day').startOf('day').valueOf()//.unix();
  const endNum = moment(timeValue.value).subtract(1, 'day').endOf('day').valueOf()//.unix();
  const list = data.filter((item) => {
    const arr = (item[8] as string).split('~');
    const num = moment(arr[0]).valueOf()//.unix()
    return startNum <= num && endNum >= num;
  })
  const num = list.reduce((a, b) => {
    return a + Number(b[7]);
    // if (b.length === 11) {
    // } else {
    //   return a + Number(b[6]);
    // }
  }, 0);
  return num;
}
/** 运行时间戳 */
function handleData2(data: any[]) {
  const startNum = moment(timeValue.value).startOf('day').subtract(1, 'day').valueOf()//.unix();
  const endNum = moment(timeValue.value).endOf('day').subtract(1, 'day').valueOf()//.unix();
  let timer = 0;
  data.forEach((item) => {
    const arr = (item[8] as string).split('~');
    const num1 = moment(arr[0]).valueOf()//.unix();
    const num2 = moment(arr[1]).valueOf();//.unix();
    if (startNum <= num1 && endNum >= num1) {
      timer += num2 - num1
    }
  })
  return timer / (60 * 1000);//时间以分钟为单位
}
/** 获取预警数据 */
function getWarningData() {
  if (timeType.value === 0) {
    getstatistics('day').then(res => {
      alarm.value = res.data.name.map((item: any, i: number) => { return { name: item, value: res.data.alert[i] } })
    })
  } else {
    getstatistics('week').then(res => {
      alarm.value = res.data.name.map((item: any, i: number) => { return { name: item, value: res.data.alert[i] } })
    })
  }

}
/** 改变时间类型选择 */
function changeType(type: number) {
  timeType.value = type;
  getnenghao();
  getWarningData();
  getDataCL();
  // const dataList = JSON.parse(JSON.stringify(dachengList));
  // dachengList.splice(0,dachengList.length);
  // dachengList.push(...dataList);
}
/** 改变时间选择 */
function changeTime(time: string) {
  timeValue.value = time;
  getnenghao();
  getData();
  getorderForm();
}
/** 安全天数 */
function getSafetyFun() {
  // getSafety().then(res => {
  //   safetyNum.value = res.data
  // })
  safetyNum.value = Number(moment().format('DD'))
}
/** 获取稼动率 */
async function getJiadonglvFun() {
  /** 日期 */
  const dayStr = moment().subtract(1, 'day').format('YYYY-MM-DD');
  currentDayPlan.value = await getDapingList({ day: dayStr }).then(res => res.data.data).catch(() => undefined) ?? {};
  getDeviceParam().then(({ data: { data } }) => {
    plantLisetRuntime.value = data ?? [];
  })
}
/** 计算设备计划负荷时常 */
function sumPlanTime(data: Array<string[]>) {
  let planTime = 0;
  data.forEach(item => {
    if (item[8]) {
      const [startDate, endDate] = item[8].split("~");
      planTime += moment(endDate).diff(moment(startDate)) ?? 0;
    }
  })
  return planTime;
}
/**获取异常照片 */
function getWarnImgTypeList(){
  getWarnImgType().then((res: any)=>{
    imgWarnTypeList.value = res;
  });
}
/**获取异常照片 */
function getWarnImgList(dir: string){
  imgsWarnList.value = [];
  modelLoading.value = true;
  getWarnImg(dir).then((res: any)=>{
    imgsWarnList.value = res?.data?.map((ele: string)=>{
      return imgRequstUrl + ele;
    });
  }).finally(()=>{
    modelLoading.value = false;
  })
}
function showWarnImgDiag(dir: string, titleName: string){
  imgTitle.value = titleName;
  dialogTableVisible.value = true;
  getWarnImgList(titleName || dir);
}
/** 侦听器 */
/** 计算属性 */
// 单耗列表 5个分厂米数/5个分厂的能耗
const oneclist = computed(() => {
  const data = defaultClist.value.map(item => {
    if (item.name !== "厂区总览") {
      const info = fahuo.value.find(item2 => item2.Group?.includes(item.name));
      if (timeType.value) {
        return {
          name: info?.Group,
          num: (Number(info?.Week) ? (Number(item.num) / Number(info?.Week)) : 0),//* 1000000
          value: ((Number(info?.Week) ? (Number(item.num) / Number(info?.Week)) : 0) * 1000).toFixed(2) + '元/千米'//'gCO2e' //* 1000000
        }
      } else {
        return {
          name: info?.Group,
          num: (Number(info?.Day) ? (Number(item.num) / Number(info?.Day)) : 0), //* 1000000
          value: ((Number(info?.Day) ? (Number(item.num) / Number(info?.Day)) : 0) * 1000).toFixed(2) + '元/千米' // 'gCO2e' //* 1000000
        }
      }
    } else {
      return { name: "厂区总览", value: "0", num: 0 }
    }
  })
  let nums = 0
  data.forEach((item, i) => {
    if (i !== data.length - 1) {
      nums += Number(item.num);
    }
  })
  data[data.length - 1].num = nums;
  data[data.length - 1].value = nums + '元/米';// + 'gCO2e';.toFixed(2)
  return data;
})
/** 生产率 */
const shengchanRate = computed(() => {
    const data = planChanLiang.value?.map(item => {
    //production?.map(item => {
      const info = ruku.value?.find(item2 => item.name === item2.Group);
      //console.log(info,item,6666666)
      //console.log(item?.Week ? Number((Number(info?.y)/ Number(item?.Week)).toFixed(3)):0,item?.Day ? Number((Number(info?.y)/ Number(item?.Day)).toFixed(3)):0,111111)
      return {
        Group: info?.Group,
        Day: Number(info ? (Number(item.value) ? Number((Number(info.Day)/Number(item.value))).toFixed(3):0) : 0)*100,
        Week: Number(info ? (Number(item.value) ? Number((Number(info.Week)/Number(item?.value))).toFixed(3):0) : 0)*100,//(Number(item.Week) / Number(info.Week)).toFixed(3) : '0',
        value: timeType.value ? (Number(item.Week) ? Number((Number(info.Week)/Number(item?.value)).toFixed(3)) : 0) * 100 : 
            Number(info ? (Number(item.value) ? Number((Number(info.Day)/Number(item.value)).toFixed(3)) : 0):0) * 100,
        name: info?.Group,
        type: '计划达成率'
      }
    })
  return data
})
const jiadonglv = ref<any[]>([]);
const zhengPinJiaDongli = computed(()=>{
  return [...jiadonglv.value];//, ...zhengpin.value];
})
const shengchanRatePlan = computed(()=>{
  return [...shengchanRate.value];//, ... hege.value];
})
/** 超胶量图表数据 */
const coumnData = computed(() => {
  const data: { x: string; y: number }[] = [];
  chaojiao.value.forEach((item) => {
    if (timeType.value) {
      data.push({ x: item.Group || '', y: Number(item.Week) });
    } else {
      data.push({ x: item.Group || '', y: Number(item.Day) });
    }
  });
  return data;
});
const scaleX = computed(() => {
  return baseDataStore.getBaseData("scaleX") as number;
});
const clientHeight = computed(() => {
  return baseDataStore.getBaseData("clientHeight") as number;
});

</script>
<style lang="scss" scoped>
.cont {
  padding: 50px 45px 10px;
  background: url('@/assets/imgs/bg-03.png') no-repeat center;
  background-size: 100% 100%;
  background-position: center;
  margin: -40px 5px 0;

  .rowbox {
    display: flex;
    justify-content: space-between;
  }

  .box1 {
    height: 230px;
  }

  .box2 {
    // height: 120px;
    height: 240px;
    :deep(.el-carousel--vertical){
      width: 100%;
      height: 100%;
    }
  }

  .box3 {
    height: 210px;
    :deep(.el-carousel--vertical){
      width: 100%;
      height: 100%;
    }
  }

  .box1,
  .box2,
  .box3 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 17px 20px;

    .safetyBox {
      width: 100%;
      height: 100%;
      position: relative;
      display: flex;
      align-items: center;
      .safetyItems {
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
      }
    }
  }
}

.radioBox {
  flex: 1;
  margin-top: 4px;
  margin-right: 10px;
  font-size: 16px;
  float: right;
  width: 122px;
  height: 22px;
  line-height: 22px;
  text-align: center;
  border-radius: 2px;
  background: rgb(52 52 52);//#032a54;
  display: flex;
  cursor: pointer;

  .selectTime {
    // background: rgba(31, 92, 198, 0.5);
    // box-sizing: border-box;
    // border: 1px solid #40d3ff;
    // border-radius: 4px;
    // overflow: hidden;
    // box-shadow: inset 2px 2px 5px 0px rgba(0, 174, 255, 0.49);
    background: #000;
    box-sizing: border-box;
    border: 1px solid #5c5c5c;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: inset 2px 2px 5px 0px rgba(0, 0, 0, 0.49);
  }
}
.warn-img-col{
  display: flex;
  flex-wrap: wrap;
  min-height: 600px;
  max-height: 660px;
}
</style>
<style lang="scss">
:deep(.el-dialog){
  background-color: #282424!important;
}
</style>
